<template>
  <div ref="split" class="split">
    <button @click="notifyData">传值测试</button>
    <TestForm :eventData="eventData" />
  </div>
</template>

<script lang="ts" setup>
defineOptions({
  name: 'TestView'
})


import { onUnmounted, provide, ref } from 'vue';
import createTestModule from "mctp-modules-test/src/index";
import TestForm from "mctp-modules-test/src/components/index.vue";
import { handlePluginCommand } from '@/utils/commandHandler';
import type { ModuleInterface, SendCmd } from "mctp-modules-test/src/types";
import type { AxiosRequestConfig } from 'axios';
import type { Response } from '@/mctp-api';
import signalEvent from "@/utils/signalEvent";

// 1. EventData 初始值：空对象（业务数据由后端返回，初始无需填充）
const initialCalibData = { count: 0 };

// 2. 平台命令处理：完全转发插件传递的所有参数，对齐 createPost 逻辑
const handleCalibCmd: SendCmd<{
  moduleId: string;
  fixedParams?: any;
  data?: Record<string, any>;
  params?: any;
  config?: AxiosRequestConfig;
}, Response<any>> = async (moduleName, cmd, payload) => {
  if (moduleName !== "TestForm") return { code: 400, msg: "模块不匹配", data: null };

  console.log("平台接收校准指令：", cmd, payload);
  // 直接调用平台的 handlePluginCommand，传递所有参数（复刻 createPost 逻辑）
  return handlePluginCommand(
    payload?.moduleId || moduleName, // 模块ID（替代 createPost 的 url）
    payload?.fixedParams, // 固定参数（对齐 createPost 的 fixedParams）
    payload?.data, // 业务数据（对齐 createPost 的 data）
    payload?.params, // URL 参数（对齐 createPost 的 params）
    payload?.config // Axios 配置（对齐 createPost 的 config）
  );
};

// 3. 创建插件实例：完全对齐原有调用方式
const testModule: ModuleInterface<typeof initialCalibData> = createTestModule(
  initialCalibData,
  handleCalibCmd
);

const SEND_TEST_CMD_KEY = "send-test-cmd"; // 协商好的字符串Key
const GET_TEST_DATA_KEY = "get-test-data"; // 配套的“获取数据”Key

provide(SEND_TEST_CMD_KEY, (cmd: string, payload?: any) => {
  return testModule.sendCommand(cmd, payload);
});
// 注入“获取数据”方法（供插件调用）
provide(GET_TEST_DATA_KEY, testModule.eventData);

// 5. 手动初始化插件
testModule.startup();

import { useRoute } from 'vue-router'
import { onMounted } from 'vue';

/**
 * @description: 事件接收
 * @return {*}
 */
const initEvent = () => {
  const route = useRoute()
  const taskId = route.query?.taskId || "";
  signalEvent.$on(taskId as string, handleEvent);
};
const unloadEvent = () => {
  const route = useRoute()
  const taskId = route.query?.taskId || "";
  signalEvent.$off(taskId as string, handleEvent); // 卸载事件
};

type EventData = { dataName?: string; data: any };
const eventData = ref<EventData | undefined>();
const handleEvent = (param: EventData) => {
  console.log("param", param);
  eventData.value = param;
}

onMounted(() => {
  initEvent();
})

onUnmounted(() => {
  unloadEvent();
})

const businessData = ref({
  count: 0,
  status: "init",
  // 其他业务字段...
});

const notifyData = () => {
  businessData.value.count++;
  businessData.value.status = "updated";
  console.log("平台更新数据：", businessData.value);
};

</script>
<style scoped lang="scss"></style>
